import request from '@/utils/request'
import type { ApiResponse, PageResponse } from '@/types/api'
import type { OperationLog } from '@/types/system'

// 安全相关API（操作日志、安全审计等）
export const securityApi = {
  // 获取操作日志列表
  getOperationLogs: (params: {
    current?: number
    size?: number
    module?: string
    operation?: string
    username?: string
    startDate?: string
    endDate?: string
  }): Promise<ApiResponse<PageResponse<OperationLog>>> => {
    return request.get('/auth/security/operation-logs', { params })
  },

  // 导出操作日志
  exportOperationLogs: (params: {
    module?: string
    operation?: string
    username?: string
    startDate?: string
    endDate?: string
  }): Promise<void> => {
    return request.get('/auth/security/operation-logs/export', {
      params,
      responseType: 'blob'
    }).then((response: any) => {
      const blob = new Blob([response], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `operation_logs_${new Date().toISOString().slice(0, 10)}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    })
  },

  // 清空操作日志
  clearOperationLogs: (): Promise<ApiResponse<string>> => {
    return request.delete('/auth/security/operation-logs/clear')
  },

  // 获取操作日志详情
  getOperationLogDetail: (logId: string): Promise<ApiResponse<OperationLog>> => {
    return request.get(`/auth/security/operation-logs/${logId}`)
  },

  // 获取登录日志列表
  getLoginLogs: (params: {
    current?: number
    size?: number
    username?: string
    ipAddress?: string
    startDate?: string
    endDate?: string
  }): Promise<ApiResponse<PageResponse<any>>> => {
    return request.get('/auth/security/login-logs', { params })
  },

  // 导出登录日志
  exportLoginLogs: (params: {
    username?: string
    ipAddress?: string
    startDate?: string
    endDate?: string
  }): Promise<void> => {
    return request.get('/auth/security/login-logs/export', {
      params,
      responseType: 'blob'
    }).then((response: any) => {
      const blob = new Blob([response], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `login_logs_${new Date().toISOString().slice(0, 10)}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    })
  },

  // 清空登录日志
  clearLoginLogs: (): Promise<ApiResponse<string>> => {
    return request.delete('/auth/security/login-logs/clear')
  }
}

export default securityApi

